package com.hbk.base.interceptor;

import com.alibaba.fastjson.JSON;
import com.hbk.base.auth.JWTInfo;
import com.hbk.base.common.RequestInfo;
import com.hbk.base.util.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.atomic.AtomicLong;

/**
 *  优先级最高,对所有请求都放行
 *  用于日志记录,请求编号生成
 */
public class LoggerInterceptor implements HandlerInterceptor {

    private static Logger logger = LoggerFactory.getLogger("requestAPI");
    private AtomicLong atomicLong = new AtomicLong(0);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        if(request.getMethod().equalsIgnoreCase("OPTIONS")){
            return false;
        }

        RequestInfo requestInfo = new RequestInfo();
        requestInfo.setStartTime(new Date().getTime());
        long id = atomicLong.incrementAndGet();
        requestInfo.setRequestId(id);
        requestInfo.setHost(request.getRemoteAddr());
        requestInfo.setUrl(request.getRequestURI());
        requestInfo.setCode(-1);

        String authorization = request.getHeader("Authorization");
        if(StringUtil.isEmpty(authorization)){
            authorization = request.getParameter("Authorization");
        }
        if(StringUtil.isEmpty(authorization)){
            requestInfo.setToken(authorization);
        }

        Enumeration<String> headerNames = request.getHeaderNames();
        Map<String,String> headerMap = new HashMap<>();
        while(headerNames.hasMoreElements()){
            String name = headerNames.nextElement();
            headerMap.put(name,request.getHeader(name));
        }
        requestInfo.setHeaders(headerMap);

        Enumeration<String> parameterNames = request.getParameterNames();
        Map<String,String> paramMap = new HashMap<>();
        while(parameterNames.hasMoreElements()){
            String name = parameterNames.nextElement();
            paramMap.put(name,request.getParameter(name));
        }
        requestInfo.setParams(paramMap);
        RequestInfo.set(requestInfo);

        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        RequestInfo requestInfo = RequestInfo.get();
        if(requestInfo==null){
            //请求结束，清除ThreadLocal中的信息
            RequestInfo.remove();
            JWTInfo.remove();
            return;
        }
        long current = new Date().getTime();
        long time = current - requestInfo.getStartTime();
        requestInfo.setTime((int)time);
        logger.info("{} {}",requestInfo.getUrl(),JSON.toJSONString(requestInfo));
    }
}
